package com.jinxin.platform.cdcardpassmgr.service.impl;

import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cdcardpassmgr.bean.CdcardpassmgrDevice;
import com.jinxin.platform.cdcardpassmgr.common.SysUserVO;
import com.jinxin.platform.cdcardpassmgr.mapper.CdcardpassmgrDeviceMapper;
import com.jinxin.platform.cdcardpassmgr.rpc.CdcardpassmgrRpc;
import com.jinxin.platform.cdcardpassmgr.service.ICardpassmgrDeviceService;
import com.jinxin.platform.cdcardpassmgr.task.CdcardpassmgrQuartzScheduler;
import com.jinxin.platform.cdcardpassmgr.utils.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-07-06
 * @Author: Lingnan
 **/
@Service
@Slf4j
public class CardpassmgrDeviceServiceImpl implements ICardpassmgrDeviceService {
    @Autowired
    private CdcardpassmgrDeviceMapper deviceMapper;
    @Resource
    private IdWorker idWorker;
    @Autowired
    private CdcardpassmgrRpc cdcardpassmgrRpc;
    @Autowired
    private CdcardpassmgrQuartzScheduler scheduler;

    @Override
    public List<CdcardpassmgrDevice> list(HashMap param) {
        return deviceMapper.list(param);
    }

    @Override
    public List<CdcardpassmgrDevice> listPage(HashMap param) {
        return deviceMapper.listPage(param);
    }

    @Override
    public int listPageCount(HashMap param) {
        return deviceMapper.listPageCount(param);
    }

    @Override
    public JsonResult delete(String id) {
        if(StringUtils.isEmpty(id)){
            return JsonResult.error("记录Id不存在");
        }
        int result = deviceMapper.deleteByKey(id);
        if(result > 0){
            // 删除定时任务
            CdcardpassmgrDevice device = deviceMapper.selectByKey(id);
            if(device != null){
                try {
                    scheduler.deleteJob(id,"group"+id);
                } catch (SchedulerException e) {
                    log.error(e.toString());
                }
            }
            return JsonResult.ok("删除成功","");
        }
        return JsonResult.error("删除失败");
    }

    @Override
    public JsonResult saveOrUpdate(CdcardpassmgrDevice device) {
        if (device == null){
            return JsonResult.error("参数错误，操作失败");
        }
        String id = device.getId();
        int count;
        String msg = "";
        if(StringUtils.isEmpty(id)){
            device.setId(String.valueOf(idWorker.nextId()));
            device.setCreateTime(LocalDateTime.now());
            count = deviceMapper.insert(device);
            msg = "新增成功";
        }else {
            if(!device.isNoNeedLogin()){
                SysUserVO currentUser = cdcardpassmgrRpc.getCurrentUser();
                if(currentUser == null){
                    return JsonResult.error("获取当前用户信息失败");
                }
                String userName = currentUser.getUserName();
                String configUser = !StringUtils.isEmpty(userName) ? userName : currentUser.getUserAccount();
                device.setConfigUserId(currentUser.getUserId());
                device.setConfigUser(configUser);
            }
            device.setUpdateTime(LocalDateTime.now());
            device.setConfigStatus(1);//已配置
            CdcardpassmgrDevice oldDevice = deviceMapper.selectByKey(id);
            count = deviceMapper.updateByKey(device);
            if(count > 0){ //更新定时任务时间
                if(oldDevice != null && !StringUtils.isEmpty(device.getIntervalSecond())){
                    Integer oldTime = oldDevice.getIntervalSecond();
                    Integer newTime = device.getIntervalSecond();
                    String cron = "0/"+ newTime +" * * * * ? ";
                    if(oldTime == null && newTime > 0){
                        try {
                            scheduler.addJob(id,"group"+id,cron);
                        } catch (SchedulerException e) {
                            log.error(e.toString());
                        }
                    }else if(oldTime != null && !oldTime.equals(newTime)){
                        try {
                            scheduler.modifyJob(id,"group"+id,cron);
                        } catch (SchedulerException e) {
                            log.error(e.toString());
                        }
                    }
                }
            }
            msg = "更新成功";
        }
        if(count > 0){
            return JsonResult.ok(msg,"");
        }else {
            return JsonResult.error("操作失败，请重试");
        }
    }

    @Override
    public CdcardpassmgrDevice getById(String id) {
        return deviceMapper.selectByKey(id);
    }
}
